/**  

* @Title: LoginAction.java 

* @Package com.gxbadge.action 

* @Description: TODO(用一句话描述该文件做什么) 

* @author CST

* @version V1.0  

*/ 

package com.gxbadge.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.aspectj.util.FileUtil;
import org.json.simple.JSONObject;

import com.gxbadge.action.base.BaseAction;
import com.gxbadge.model.Article;
import com.gxbadge.model.Image;
import com.gxbadge.model.Language;
import com.gxbadge.model.Navigation;
import com.gxbadge.util.DateTimeUtil;
import com.gxbadge.vo.ArticleVo;
import com.opensymphony.xwork2.ActionContext;

public class ArticleAction extends BaseAction {
	
	private Article arti;
	
	public Article getArti() {
		return arti;
	}
	public void setArti(Article arti) {
		this.arti = arti;
	}
	private String[] selectedNavId;
	
	public String[] getSelectedNavId() {
		return selectedNavId;
	}
	public void setSelectedNavId(String[] selectedNavId) {
		this.selectedNavId = selectedNavId;
	}
	
	private Navigation nav;
	private List<Navigation> navList;
	public Navigation getNav() {
		return nav;
	}
	public void setNav(Navigation nav) {
		this.nav = nav;
	}
	
	public List<Navigation> getNavList() {
		return navList;
	}
	public void setNavList(List<Navigation> navList) {
		this.navList = navList;
	}
	public String insert_arti() throws Exception{
		
		if(this.getSelectedNavId()!=null){
			this.setSelectedNavId(null);
		}
		if(this.getNav()!=null&&this.getNav().getNavId()!=null){
			
			Navigation n = adminManager.findNavByNavId(this.getNav().getNavId());
			if(n!=null){
				this.setNav(n);
				List<Navigation> nList = adminManager.findNavListByNavPid(n.getNavId());
				if(nList!=null&&nList.size()>=1){
					this.setNavList(nList);
				}
			}
		}
		
		return "arti_insert_success";
	}
	
	private HttpServletRequest request;
	private HttpServletResponse response;	
	private File imgFile;
    private String imgFileFileName;  
    private String savePath;
    private String imgWidth;
    private String imgHeight;
	public String getSavePath() {
		return savePath;
	}
    public File getImgFile() {
		return imgFile;
	}
	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	public String getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(String imgWidth) {
		this.imgWidth = imgWidth;
	}

	public String getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(String imgHeight) {
		this.imgHeight = imgHeight;
	}

	public String upload_artiImage() throws Exception{
		
		request = ServletActionContext.getRequest();
    	response = ServletActionContext.getResponse();
        response.setContentType("text\\html; charset=UTF-8");
        ActionContext ctx = ActionContext.getContext();
        
        // 文件保存目录路径
        
        String navDir = "";
        if(ctx.getSession().get("nav")!=null){
        	navDir = ctx.getSession().get("nav").toString();
        	
        }
        if(!navDir.equals("")){
        	savePath=ServletActionContext.getServletContext().getRealPath("\\upload") + "\\"+navDir+"\\";
        }else{
        	savePath=ServletActionContext.getServletContext().getRealPath("\\upload") + "\\";
        }
        
       
        // 文件保存目录URL
        String saveUrl = "http://" +request.getServerName() + ":"+request.getServerPort() + request.getContextPath()+"/upload/"+navDir+"/";
      
        // 定义允许上传的文件扩展名
        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
        // 最大文件大小
        long maxSize = 2000000;
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        if (this.getImgFile() == null) {
            out.println(getError("请选择文件。"));
            return null;
        }

        // 检查目录
        File uploadDir = new File(this.getSavePath());
        
        if (!uploadDir.isDirectory()) {
        	uploadDir.mkdirs();
            
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            out.println(getError("上传目录没有写权限。"));
            return null;
        }
        // 创建文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "\\";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
		String fileExt = imgFileFileName.substring(this.getImgFileFileName().lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
            out.println(getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。"));
            return null;
        }
        if (imgFile.length() > maxSize) {
            out.println(getError("[ " + imgFileFileName + " ]超过单个文件大小限制，文件大小[ " + imgFile.length() + " ]，限制为[ " + maxSize + " ] "));
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        
        try {
            FileUtil.copyFile(imgFile, uploadedFile);
            JSONObject obj = new JSONObject();
            obj.put("error", 0);
            obj.put("url", saveUrl + newFileName);
            out.println(obj.toString());
           
        } catch (IOException e) {
            e.printStackTrace();
        }

        Image image=new Image();
        image.setImageSaveName(newFileName);
        if(!navDir.equals("")){
        	image.setImageSavePath("upload/"+ymd+"/");
        }else{
        	image.setImageSavePath("upload/"+navDir+"/"+ymd+"/");
        }
        
        image.setImageUrl(saveUrl+newFileName);
        adminManager.add_image(image);
        List<Image> imageList = new ArrayList<Image>();
        
        if(ctx.getSession().get("imageList")!=null){
        	imageList.addAll((List<Image>) ctx.getSession().get("imageList")); 
        	imageList.add(image);
        }else{	
        	imageList.add(image);
        }
       
        ctx.getSession().put("imageList", imageList);

		return null;
	}
	private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toString();
    }
	
	public String add_arti() throws Exception{
		
		
		 ActionContext ctx = ActionContext.getContext();
		 if(this.getArti().getUploadDate()!=null){
			 String uploadDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this.getArti().getUploadDate());
			 Timestamp timestamp = Timestamp.valueOf(uploadDate);
			 this.getArti().setUploadDate(timestamp);
		 }else{
			 
			 Timestamp timestamp = DateTimeUtil.getNowTime();
			 this.getArti().setUploadDate(timestamp);
			 
		 }
		 
		 this.getArti().setClickNums(0);
		 this.getArti().setDeleteFlag(false);
		 this.getArti().setHotFlag(false);
		 this.getArti().setPermFlag(false);
		 
		 if(this.getSelectedNavId()!=null){
			 
			 
			 int navId = Integer.parseInt(this.getSelectedNavId()[0]);
			 Navigation n = adminManager.findNavByNavId(navId);
			 if(n!=null){
				 this.getArti().setNav(n);
				 this.setNav(n);
				 Language lang = n.getLang();
				 if(lang!=null){
					 this.getArti().setLang(lang);
				 }	
			 }
		 }
		
		 
		 adminManager.add_arti(this.getArti());
		 
		 if(ctx.getSession().get("imageList")!=null){
			 
			 List<Image> imageList = (List<Image>)(ctx.getSession().get("imageList"));
			 if(imageList!=null){
				 for(int i=0;i<imageList.size();i++){
					 Image image = imageList.get(i);
					 if(image!=null){
						 image.setArti(this.getArti());
					 }
					 
				 }
			 }
			 ctx.getSession().remove("imageList");
		 }
		 
		return "arti_add_success";
	}
	private static int pageSize = 20;
	private int pageNo;
	private int pageCount;
	private long artiTotalCount;
	
	public int getPageNo() {
		return pageNo;
	}
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}
	public int getPageCount() {
		return pageCount;
	}
	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}
	public long getArtiTotalCount() {
		return artiTotalCount;
	}
	public void setArtiTotalCount(long artiTotalCount) {
		this.artiTotalCount = artiTotalCount;
	}
	public int getPageSize() {
		return pageSize;
	}
	private List<ArticleVo> artiVoList;
	
	public List<ArticleVo> getArtiVoList() {
		return artiVoList;
	}
	public void setArtiVoList(List<ArticleVo> artiVoList) {
		this.artiVoList = artiVoList;
	}
	
	private String paramNavId;
	
	public String getParamNavId() {
		return paramNavId;
	}
	public void setParamNavId(String paramNavId) {
		this.paramNavId = paramNavId;
	}
	public String find_artiList() throws Exception{
		
		
		if(this.getParamNavId()!=null){
			
			
			int navId = Integer.parseInt(this.getParamNavId());
			List<Navigation> navList = new LinkedList<Navigation>();
			Navigation n = adminManager.findNavByNavId(navId);
			if(n!=null){
				this.setNav(n);
				navList.add(n);
				List<Navigation> nList = adminManager.findNavListByNavPid(n.getNavId());
				if(nList!=null&&nList.size()>=1){
					navList.addAll(nList);
				}
			}
			if(navList!=null&&navList.size()>=1){
				
				long artiTotalCount = adminManager.find_artiTotalCount(navList);
				this.setArtiTotalCount(artiTotalCount);
				int pageCount = (int) (this.getArtiTotalCount()/this.getPageSize()+1);
				this.setPageCount(pageCount);
				if(this.getPageNo()==0){
					this.setPageNo(1);
				}
				if(this.getArtiTotalCount()==0){
					this.setPageNo(0);
					this.setPageCount(0);
				}
				
				if(this.getPageNo()==1){
					
					int offset = 0;
					List<Article> artiList = adminManager.findArtiListByNavList(navList, offset, this.getPageSize());
					if(artiList!=null&&artiList.size()>=1){
						List<ArticleVo> avList = new LinkedList<ArticleVo>();
						for(int i=0;i<artiList.size();i++){
							
							ArticleVo av = new ArticleVo();
							Article arti = artiList.get(i);
							av.setArtiId(arti.getArtiId());
							av.setArtiTitle(arti.getTitle());
							av.setAuthor(arti.getAuthor());
							av.setClickNums(arti.getClickNums());
							av.setHotFlag(arti.getHotFlag());
							Navigation nv = arti.getNav();
							if(n!=null){
								av.setNavId(nv.getNavId());
								av.setNavTitle(nv.getTitle());
							}
							av.setPermFlag(arti.getPermFlag());
							av.setPriority(arti.getPriority());
							av.setUploadDate(arti.getUploadDate());
							avList.add(av);
						}
						if(avList!=null&&avList.size()>=1){
							this.setArtiVoList(avList);
						}
						
					}
				}
				if(this.getPageNo()>1&&this.getPageNo()<=this.getPageCount()){
					
					int offset = (this.getPageNo()-1)*this.getPageSize();
					List<Article> artiList = adminManager.findArtiListByNavList(navList, offset, this.getPageSize());
					if(artiList!=null&&artiList.size()>=1){
						List<ArticleVo> avList = new LinkedList<ArticleVo>();
						for(int i=0;i<artiList.size();i++){
							ArticleVo av = new ArticleVo();
							Article arti = artiList.get(i);
							av.setArtiId(arti.getArtiId());
							av.setArtiTitle(arti.getTitle());
							av.setAuthor(arti.getAuthor());
							av.setClickNums(arti.getClickNums());
							av.setHotFlag(arti.getHotFlag());
							Navigation nv = arti.getNav();
							if(nv!=null){
								av.setNavId(nv.getNavId());
								av.setNavTitle(nv.getTitle());
							}
							av.setPermFlag(arti.getPermFlag());
							av.setPriority(arti.getPriority());
							av.setUploadDate(arti.getUploadDate());
							avList.add(av);
						}
						if(avList!=null&&avList.size()>=1){
							this.setArtiVoList(avList);
						}
					}
				}
				
			}
			this.setParamNavId(null);
		}else if(this.getNav()!=null&&this.getNav().getNavId()!=null){
				
			
			List<Navigation> navList2 = new LinkedList<Navigation>();
			Navigation n2 = adminManager.findNavByNavId(this.getNav().getNavId());
			if(n2!=null){
				this.setNav(n2);
				navList2.add(n2);
				List<Navigation> nList = adminManager.findNavListByNavPid(n2.getNavId());
				if(nList!=null&&nList.size()>=1){
					navList2.addAll(nList);
				}
			}
			if(navList2!=null&&navList2.size()>=1){
				
				long artiTotalCount = adminManager.find_artiTotalCount(navList2);
				this.setArtiTotalCount(artiTotalCount);
				int pageCount = (int) (this.getArtiTotalCount()/this.getPageSize()+1);
				this.setPageCount(pageCount);
				if(this.getPageNo()==0){
					this.setPageNo(1);
				}
				if(this.getArtiTotalCount()==0){
					this.setPageNo(0);
					this.setPageCount(0);
				}
				
				if(this.getPageNo()==1){
					
					int offset = 0;
					List<Article> artiList = adminManager.findArtiListByNavList(navList2, offset, this.getPageSize());
					if(artiList!=null&&artiList.size()>=1){
						List<ArticleVo> avList = new LinkedList<ArticleVo>();
						for(int i=0;i<artiList.size();i++){
							
							ArticleVo av = new ArticleVo();
							Article arti = artiList.get(i);
							av.setArtiId(arti.getArtiId());
							av.setArtiTitle(arti.getTitle());
							av.setAuthor(arti.getAuthor());
							av.setClickNums(arti.getClickNums());
							av.setHotFlag(arti.getHotFlag());
							Navigation nv = arti.getNav();
							if(nv!=null){
								av.setNavId(nv.getNavId());
								av.setNavTitle(nv.getTitle());
							}
							av.setPermFlag(arti.getPermFlag());
							av.setPriority(arti.getPriority());
							av.setUploadDate(arti.getUploadDate());
							avList.add(av);
						}
						if(avList!=null&&avList.size()>=1){
							this.setArtiVoList(avList);
						}
						
					}
				}
				if(this.getPageNo()>1&&this.getPageNo()<=this.getPageCount()){
					
					int offset = (this.getPageNo()-1)*this.getPageSize();
					List<Article> artiList = adminManager.findArtiListByNavList(navList2, offset, this.getPageSize());
					if(artiList!=null&&artiList.size()>=1){
						List<ArticleVo> avList = new LinkedList<ArticleVo>();
						for(int i=0;i<artiList.size();i++){
							ArticleVo av = new ArticleVo();
							Article arti = artiList.get(i);
							av.setArtiId(arti.getArtiId());
							av.setArtiTitle(arti.getTitle());
							av.setAuthor(arti.getAuthor());
							av.setClickNums(arti.getClickNums());
							av.setHotFlag(arti.getHotFlag());
							Navigation nv = arti.getNav();
							if(nv!=null){
								av.setNavId(nv.getNavId());
								av.setNavTitle(nv.getTitle());
							}
							av.setPermFlag(arti.getPermFlag());
							av.setPriority(arti.getPriority());
							av.setUploadDate(arti.getUploadDate());
							avList.add(av);
						}
						if(avList!=null&&avList.size()>=1){
							this.setArtiVoList(avList);
						}
					}
				}
			}
		}
		
		return "artiList_find_success";
	}
	
	public String upload_arti() throws Exception{
		
		if(this.getArti()!=null&&this.getArti().getArtiId()!=null){
			
			Article arti = adminManager.findArtiByArtiId(this.getArti().getArtiId());
			if(arti!=null){
				String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(arti.getUploadDate());
		        Timestamp timestamp = Timestamp.valueOf(nowTime);
		        arti.setUploadDate(timestamp);
				this.setArti(arti);
				Navigation nav = arti.getNav();
				if(nav!=null){
					this.setNav(nav);
					List<Navigation> nList = adminManager.findNavListByNavPid(nav.getNavId());
					if(nList!=null&&nList.size()>=1){
						this.setNavList(nList);
					}
				}

			}
		}

		return "arti_upload_success";
	}
	
	public String modify_arti() throws Exception{
		
		ActionContext ctx = ActionContext.getContext();
		if(this.getArti().getUploadDate()!=null){
			String uploadDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this.getArti().getUploadDate());
			Timestamp timestamp = Timestamp.valueOf(uploadDate);
			this.getArti().setUploadDate(timestamp);
		}else{
	 
			Timestamp timestamp = DateTimeUtil.getNowTime();
			this.getArti().setUploadDate(timestamp);
	 
		}
		 
		 this.getArti().setDeleteFlag(false);
		 
		 this.getArti().setPermFlag(false);
		 
		 if(this.getSelectedNavId()!=null){

			int navId = Integer.parseInt(this.getSelectedNavId()[0]);
			Navigation n = adminManager.findNavByNavId(navId);
			if(n!=null){
				this.getArti().setNav(n);
				this.setNav(n);
				Language lang = n.getLang();
				if(lang!=null){
					this.getArti().setLang(lang);
				}	
			 }
		 }

		 adminManager.modify_arti(this.getArti());
		 
		 if(ctx.getSession().get("imageList")!=null){
			 
			 List<Image> imageList = adminManager.findImageByArti(this.getArti());
			 if(imageList!=null&&imageList.size()>=1){
				 for(int i=0;i<imageList.size();i++){
					 adminManager.del_image(imageList.get(i));
				 }
			 }
			 List<Image> iList = (List<Image>)(ctx.getSession().get("imageList"));
			 if(iList!=null){
				 for(int i=0;i<iList.size();i++){
					Image image = iList.get(i);
					if(image!=null){
						image.setArti(this.getArti());
					}
				}
			}
			ctx.getSession().remove("imageList");
		}
		
		return "arti_modify_success";
	}
	
	public String del_arti() throws Exception{
		
		if(this.getArti()!=null&&this.getArti().getArtiId()!=null){
			
			Article arti = adminManager.findArtiByArtiId(this.getArti().getArtiId());
			List<Image> imageList = adminManager.findImageByArti(this.getArti());
			if(imageList!=null&&imageList.size()>=1){
				for(int i=0;i<imageList.size();i++){
					adminManager.del_image(imageList.get(i));
				}
			}
			arti.setDeleteFlag(true);
			adminManager.modify_arti(arti);
		}

		return "arti_del_success";
	}
	
	
	
}
